package ru.rs.objects;

import ru.rs.interfaces.Game;
import ru.rs.interfaces.impl.AndroidGame;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class RenderView extends SurfaceView implements Runnable {

	protected Game game;

	protected Bitmap frame;

	private boolean running;

	private SurfaceHolder holder;

	private Thread renderThread = null;

	public RenderView(AndroidGame context, Bitmap fr) {

		super(context);
		game = context;
		frame = fr;
		running = false;
		holder = getHolder();
	}

	public void run() {

		Rect rect = new Rect();
		while (running) {
			if (!holder.getSurface().isValid()) {
				continue;
			}
			game.getCurrentScreen().update(0);
			game.getCurrentScreen().render(0);

			Canvas canvas = holder.lockCanvas();
			canvas.getClipBounds(rect);
			canvas.drawBitmap(frame, null, rect, null);
			holder.unlockCanvasAndPost(canvas);
		}
	}

	public void resume() {

		running = true;
		renderThread = new Thread(this);
		renderThread.start();

	}

	public void pause() {

		running = false;
		while (true) {
			try {
				if (renderThread != null) {
					renderThread.join();
					break;
				}
			} catch (InterruptedException e) {
			}
		}
	}
}
